package com.meteor.backController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.meteor.common.BlogDto;
import com.meteor.pojo.Blog;
import com.meteor.pojo.Type;
import com.meteor.service.BlogService;
import com.meteor.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class BackBlogController {

    @Resource
    private BlogService blogService;

    @Resource
    private TypeService typeService;

    /**
     * 博客根据标题查询、分页实现
     */
    @GetMapping("/blogMagt/{pageNum}")
    public String blogMagt(@PathVariable int pageNum,String title, Model model) {
        PageHelper.startPage(pageNum,5);
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(title != null,Blog::getTitle,title);
        queryWrapper.orderByDesc(Blog::getId);
        List<Blog> list = blogService.list(queryWrapper);
        PageInfo<Blog> pageInfo = new PageInfo<>(list);
        model.addAttribute("page",pageInfo);
        model.addAttribute("blogs",list);
        return "admin/blogMagt";
    }

    /**
     * 来到博客新增页面
     */
    @GetMapping("/blogSend")
    public String blogSend(Model model) {
        List<Type> list = typeService.list();
        model.addAttribute("types",list);
        return "admin/blogSend";
    }

    /**
     * 博客新增
     */
    @PostMapping("/add")
    public String add(BlogDto blogDto) {
        blogService.saveWithTitle(blogDto);
        return "redirect:/admin/blogMagt/1";
    }

    /**
     * 博客删除
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        blogService.removeById(id);
        return "redirect:/admin/blogMagt/1";
    }

    /**
     * 进入博客修改页面
     */
    @GetMapping("/update/{id}")
    public String blogUpdate(@PathVariable Integer id,Model model) {
        Blog blog = blogService.getById(id);
        model.addAttribute("blog",blog);
        return "admin/blogUpdate";
    }

    /**
     * 博客内容修改
     */
    @GetMapping("/update")
    public String update(Blog blog) {
        blogService.updateById(blog);
        return "redirect:/admin/blogMagt/1";
    }



}
